#!/usr/bin/env python
# coding: utf-8

import os
import re
import shutil
import zipfile
import time
import datetime
import string
from onshs.ne.tnxxx.tnxxxcfg_basecase import *


log_node_prefix = "mod_hot_wa"
log_node_fail = log_node_prefix+r"_fail"
log_node_success = log_node_prefix+r"_success"
log_node_summary = log_node_prefix+r"_summary"

log_file_notexisted_fail = "the file %s isn't existed"     #log_node_fail
log_connect_fail = "connect ne:%s failed" 	           #log_node_fail
log_ne_fail =  "mod_hot wa ne:%s failed" 		   #log_node_summary
log_no_lpt_cfg = "no LPT setting ne:%s "	           #log_node_fail
log_ne_fail = "mod_hot wa ne:%s failed"  		   #log_node_summary
log_ne_fail =  "mod_hot wa ne:%s failed" 		   #log_node_fail
log_ne_success = "mod_hot wa ne:%s success"                #log_node_success
log_hot_success = "ip:%s mod hold over time wa success"                            #log_node_summary
log_hot_fail = "mod_hot wa ne:%s failed"	                                   #log_node_summary
log_chss_port_fail = "mod_hot wa ne:%s ,chss %d, port %d failed"	           #log_node_summary
log_chss_port_success = "mod_hot wa ne:%s ,chss %d, port %d success"	           #log_node_summary

class TestCase(TnxxxCfg_BaseCase):
    """
    TestCase
    """
    OPTIONS = [        
        {
            'opt' : '--cfgfile',
            'dest': 'cfgfile',
            'metavar' : 'CFGFILE',
            'help' : 'the file of ip list configuration',
            'required' : False,
            'default' : "ip.txt"
        },
        {
            'opt' : '--hot',
            'dest': 'hot',
            'metavar' : 'HOT',
            'help' : 'the hot of lpt',
            'required' : False,
            'default':12 
        }
    ]
    
        #初始化信息
    def info_init(self):
        self.info_dic = {}  

        return True
    
    #得到IPLIST
    def get_iplist(self):
        iplist_filted = []                
        if os.path.isfile(os.getcwd()+r'/'+ self.iplistfile):
            iplist = open(os.getcwd()+r'/'+ self.iplistfile)            
        else:
            self.info_show(log_node_fail, log_file_notexisted_fail%(self.iplistfile))            
            return iplist_filted 
        
        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行            
            iplist_filted.append(line.strip('\n'))        
            
        iplist.close()
        
        return iplist_filted
    
    #跟LOG相关函数
    def info_show(self, node, info):
        if not self.info_dic.has_key(node):
            self.info_dic[node] = ""
        self.info_dic[node] += info + '\n'
        return True

    def info_file_clear(self):
        if os.path.exists(os.getcwd()+r'/mod_hot_wa_log'):
            shutil.rmtree(os.getcwd()+r'/mod_hot_wa_log')
        
        return True    
    
    def info_file_save(self):
        path = os.getcwd()+'/log'+'//'
        
        for node in self.info_dic:
            info_list = open(path+node+'_'+self.worktime+'.txt','a')            
            info_list.write(self.info_dic[node])
            info_list.close()
        return True
        
    #设置LPT的hot时间，单位是毫秒
    def set_lpt_hottime(self):
        #chss\port\time的列表
        chss_port_time_list_before = []
        chss_port_time_list_after  = []
        #检查所有的设置是否生效
        check_list = []
        
        #查询所有LPT的配置，解析出chss 和 port
        cmd = r"dbg_dump_lptproto_info"
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, DEV_PORT)
        #形如：m_cfg.chss[2]、m_cfg.port[7]
        chss_port_time_list_before = re.findall(r"chss.(\d+).\r\n.+port.(\d+).\r\n.+\r\n.+\r\n.+\r\n.+transfailure.(\d+).", rtn_str, 0)
    
        #判断一下chss_port_time_list_before是否为空
        if chss_port_time_list_before == []:
            #记录该ip不存在lpt配置
            self.info_show(log_node_fail, log_no_lpt_cfg%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, log_ne_fail%(self.get_ne_ip(0)))
            self.ret_value.append("false")
            return False
        else:
            for chss_port_time in chss_port_time_list_before:
                #设置lpt的hot时间
                cmd = r"dbg_lpt_set_timer(%d,%d,%d*1000,1)" % (int(chss_port_time[0]), int(chss_port_time[1]), int(self.hot))
                rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, DEV_PORT)
        
         #设置时间以后，查询所有LPT的配置，解析出transfailure，看是否设置为目标值，目前是全部设置，只要查询所有的就可以了
        cmd = r"dbg_dump_lptproto_info"
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, DEV_PORT)
        #形如：m_cfg.chss[2]、m_cfg.port[7]
        chss_port_time_list_after = re.findall(r"chss.(\d+).\r\n.+port.(\d+).\r\n.+\r\n.+\r\n.+\r\n.+transfailure.(\d+).", rtn_str, 0)
        
        #判断一下chss_port_time_list_after是否为空
        if chss_port_time_list_after == []:
            self.ret_value.append("false")
            return False
        else:
            for chss_port_time_before in chss_port_time_list_before:
                for chss_port_time in chss_port_time_list_after:
                    if (chss_port_time_before[0] == chss_port_time[0]) and (chss_port_time_before[1] == chss_port_time[1]) and (int(chss_port_time[2]) == int(self.hot)*1000): 
                        self.info_show(log_node_success, log_chss_port_success%(self.get_ne_ip(0),int(chss_port_time_before[0]),int(chss_port_time_before[1])))
                        break
                else:
                    #没有找到或者值不符合期望
                    self.info_show(log_node_fail, log_chss_port_fail%(self.get_ne_ip(0),int(chss_port_time_before[0]),int(chss_port_time_before[1])))
                    check_list.append("false")                    
                        
        if check_list != []:
            self.ret_value.append("false")
            return False
                    
        return True
    
    def _execute(self):
        self.hot = self.options.hot
        self.info_init()
        self.ret_value = []
        
        worktime = str(datetime.datetime.now())
        self.worktime = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        self.iplistfile = self.options.cfgfile
        
        self.info_show(log_node_summary, "The operation begin time %s \n"%(self.worktime))
        
        ip_list = self.get_iplist()         
   
        for ip in ip_list:
            self.set_ne_ip(0, ip)
            
            #设置lpt的hot时间
            if self.set_lpt_hottime():
                self.info_show(log_node_success, log_ne_success%(self.get_ne_ip(0)))
                self.info_show(log_node_summary, log_hot_success%(ip))
            else:
                self.info_show(log_node_fail, log_ne_fail%(self.get_ne_ip(0)))
                self.info_show(log_node_summary, log_hot_fail%(ip))
            
        """
        #检查所有网元的LPT是否设置成功
        if  self.ret_value == []:
            self.info_show(log_node_summary, log_hot_success%(ip))
        else:
            self.info_show(log_node_summary, log_hot_fail%(ip))
        """
        
        worktime = str(datetime.datetime.now())
        self.worktime_end = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.info_show(log_node_summary, "\nThe operation end time %s "%(self.worktime_end))

        self.info_file_save() 
        return True
    
if __name__ == "__main__" :
    case = TestCase()
    case.execute()
